<style type="text/css" scoped>
.product-info {
    width: 100%;
    display: flex;
    position: relative;
}
.confirm-btn {
    width: 100%;
    height: 44px;
    background: #dd3022;
    color: #fff;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.icon-close {
    position: absolute;
    right: 4px;
    top: 4px;
    font-size: 26px;
    color: #666;
}
.product-info .product-image {
    width: 2.4rem;
    height: 2.4rem;
    position: relative;
}
.product-info .product-image img {
    position: absolute;
    width: 2rem;
    height: 2rem;
    left: 6px;
    bottom: 7px;
    border-radius: 4px;
    box-shadow: 0 0 1px rgba(0,0,0,.5);
}
.product-info .product-tip {
    flex: 1;
    position: relative;
}
.product-price {
    padding-top: 16px;
}
.product-price .dp-price {
	color: red;
	font-size: 16px;
}
.product-price .sc-price {
	margin-left: 10px;
	font-size: 13px;
	color: #666;
	text-decoration: line-through;
}
.product-detail-richtext {
    padding: 4px;
}
.specs-item {
    padding: 6px 0 12px 0;
}
.specs-item:not(:last-child) {
    margin-bottom: 1px;
}
.specs-item-button {
    margin-right: 6px;
    border-radius: 4px;
    display: inline-block;
    padding: 6px;
    text-align: center;
    box-shadow: 0 0 1px rgba(0,0,0,.2);
    min-width: 30px;
}
.specs-item-name {
    height: 30px;
    line-height: 30px;
}
.specs-container {
    padding-left: 10px;
    background: #fff;
}

.product-num {
    padding: 10px;
    display: flex;
    font-size: 14px;
}

.product-num .tip {
    width: 100px;
}
.action-btn-container {
    flex: 1;
}
.action-btn-container .action-btn-group {
    float: right;
    display: flex;
    box-sizing: border-box;
    width: 80px;
}
.action-btn-container .action-btn-group span {
    flex: 1;
    justify-content: center;
    align-items: center;
    display: flex;
    font-size: 14px;
}
.action-btn-container .action-btn-group span.action-disabled {
	color: #c8c9cc;
}
.action-btn-container .action-btn-group span.cart-item-count {
	margin: 0 2px;
}

.action-btn-container .action-btn-group span:first-child, .action-btn-container  .action-btn-group span.cart-item-count, .action-btn-container .action-btn-group span:last-child {
    background: #f7f7f7;
    width: 24px;
    height: 24px;
}
.buy-count {
    color: #fe0000;
}
.product-picker-action-wrap {
	display: flex;
	justify-content: center;
	align-items: center;
}
.confirm-btn {
	flex: 1;
    height: 44px;
    color: #fff;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.confirm-btn.join-cart {
	background: #dd3022;
}
.confirm-btn.buy-now {
	background: #ff5c5c;
}
.confirm-btn.join-cart.confirm-btn-disabled {
	background: rgba(0, 0, 0, .6);
}
.confirm-btn.buy-now.confirm-btn-disabled {
	background: rgba(0, 0, 0, .4);
}
.mint-popup-4 {
    width: 9rem;
}
.specs-item-button.active {
    background: red;
    color: #fff;
}
.specs-item-button.disabled {
    background: #eee;
}
.specs-item-button.normal {
    background: #fff;
}
.product-spec-wrap {
	max-height: 380px;
	min-height: 200px;
	overflow-y: auto;
}
</style>
<template>
	<mt-popup :close-on-click-modal="false" v-model="joinCartModalVisible" @input="cartModalChange" class="mint-popup-4">
		<div class="product-info scale-1px">
	        <div class="product-image">
	            <img :src="curProductItem.picture||productInfo.productImg">
	        </div>
	        <div class="product-tip">
	            <div class="product-price">
	                <span class="dp-price">¥{{curProductItem.dpPrice||productInfo.dpPrice}}</span><span class="sc-price">¥{{curProductItem.scPrice||productInfo.scPrice}}</span>
	            </div>
	            <div class="product-detail">
	                {{curProductItem.id?'商品编号'+curProductItem.code:'请选择商品规格'}}
	            </div>
	        </div>
	        <span class="icon-close" @click="joinCartModalVisible = false"></span>
	    </div>
	    <div class="product-spec-wrap">
		    <div class="specs-container">
		        <div class="specs-item scale-1px" v-for="(specsItem, index) in specs" :key="specsItem.id">
		            <div class="specs-item-name">
		                {{specsItem.name}}
		            </div>              
		            <div class="clearfix">
		                <span class="specs-item-button pull-left" @click="tabInfoChange(index, specsItemIndex, child, $event)" :class="{disabled:child.notClick, active:child.isActive}"  v-for="(child, specsItemIndex) in specsItem.child" :key="child.id">
		                    {{child.name}}
		                </span>
		            </div>
		        </div>
		    </div>
	    </div>

	    <div class="specs-container">
	        <div class="specs-item scale-1px" v-for="(attribute, index) in attributes" :key="attribute.attributeId">
	            <div class="specs-item-name">
	                {{attribute.attributeName}}
	            </div>              
	            <div class="clearfix">
	                <span class="specs-item-button pull-left" :class="{active:attribute.selectAttributeItemId == attributeItem.attributeItemId}" @click="setAttributeItemId(attribute, attributeItem)"  v-for="attributeItem in attribute.attributeItemList" :key="attributeItem.attributeItemId">
	                    {{attributeItem.attributeItemName}}
	                </span>
	            </div>
	        </div>
	    </div>

	    <div class="specs-container">
	        <div class="specs-item scale-1px" v-for="(addon, index) in addons" :key="addon.addonId">
	            <div class="specs-item-name">
	                {{addon.addonName}}
	            </div>              
	            <div class="clearfix">
	                <span class="specs-item-button pull-left"  v-for="addonItem in addon.addonItemList" :class="{active:addon.selectAddonItemId == addonItem.addonItemId}" @click="setAddonItemId(addon, addonItem)" :key="addonItem.addonItemId">
	                    {{addonItem.addonItemName}} {{addonItem.price ? '¥'+ addonItem.price : ''}}
	                </span>
	            </div>
	        </div>
	    </div>

	    <div class="product-num">
	        <div class="tip">
	            购买数量：
	        </div>
	        <div class="action-btn-container clearfix">
	            <div class="action-btn-group">
	                <span @click="desCount" :class="[curCount <=1 ?'action-disabled':'']">-</span><span class="buy-count cart-item-count">{{curCount}}</span><span @click="addCount">+</span>
	            </div>
	        </div>
	    </div>
	    <div class="split-line"></div>
	    <div class="product-picker-action-wrap">
	    	<div class="confirm-btn buy-now" :class="[btnDisabledStatus ? 'confirm-btn-disabled' : '']" @click="buyNow">
	            立即购买
	        </div>
		    <div class="confirm-btn join-cart"  :class="[btnDisabledStatus ? 'confirm-btn-disabled' : '']" @click="addToCart('addCart')">
	            加入购物车
	        </div>
        </div>
	</mt-popup>
</template>
<script type="text/javascript">
	import utils from '@utils'
	import { getProductDetail, addToCart } from './api'
	Array.prototype.combination = function (num) {
	    var r = [];
	    (function f(t, a, n) {
	       if (n == 0) return r.push(t);
	       for (var i = 0, l = a.length; i <= l - n; i++) {
	           f(t.concat(a[i]), a.slice(i + 1), n - 1);
	       }
	    })([], this, num);
	    return r;
	}
	export default {
		data() {
			return {
				productInfo: {
	                sowImg: [],
	                productItems: [],
	                id: null,
	                code: null,
	                name: '',
	                productImg: '',
	                scPrice: '',
	                dpPrice: '',
	                productDetail: '',
	            },

	            curCount: 1,
				specs: [],
	            productItemsObj: {},
	            SKUResult: {},
	            haveChangedId: [],

	            joinCartModalVisible: this.value,

	            attributes: [],
	            addons: []
			}
		},
		props: ['value', 'goodsItemDetail'],
		computed:{
	        curProductItem: function() {
	            if(this.productItemsObj[this.haveChangedId.join(";")]) {
	                return this.productItemsObj[this.haveChangedId.join(";")]
	            } else {
	                return {};
	            }
	        },
	        btnDisabledStatus() {
	        	var data = this.productInfo
	        	if(data.type == 'MULTIPLE') {
	        		if(!this.curProductItem.id) {
	        			return true
	        		}
	        	}

	        	for(var i=0;i<this.attributes.length;i++) {
	        		if(!this.attributes[i].selectAttributeItemId) {
	        			return true
	        		}
	        	}

	        	return false
	        },
	        productPriceObj() {
	        	let dpPrice = this.curProductItem.dpPrice||this.productInfo.dpPrice
	        	let scPrice = this.curProductItem.scPrice||this.productInfo.scPrice
	        	
	        	this.addons.filter(item => item.selectAddonItemId).forEach(item => {
	        		for(var i=0;i<item.addonItemList.length;i++) {
	        			if(item.addonItemList[i].addonItemId == item.selectAddonItemId) {
	        				console.log('item.addonItemList', item.addonItemList)
	        				dpPrice += item.addonItemList[i].price;
	        				scPrice += item.addonItemList[i].price;
	        				break;
	        			}
	        		}
	        	})

	        	return {
	        		dpPrice: dpPrice,
	        		scPrice: scPrice
	        	}
	        }
	    },
	    mounted() {
	    	var data = JSON.parse(JSON.stringify(this.goodsItemDetail));
	    	this.sowImg = data.sowImg;
            this.productInfo = data;

            // SKU 逻辑
            if(data.type == 'MULTIPLE') { //多sku
		    	var defaultSku = data.productItems[0]
		    	var specs = defaultSku.specs.slice(0)
	            
	            this.initKeys(data.specs);
	            this.initProductItems(data.productItems);
	            this.initSKU();
	            this.initDisabledSpecItem();
	            this.initDefaultSku(specs)
            }

            // 属性
        	this.attributes = (data.attributes||[]).map(item=> {
        		item.selectAttributeItemId = item.attributeItemList[0].attributeItemId
        		return Object.assign({}, item)
        	})

            // 附属品
        	this.addons = (data.addons||[]).map(item=> {
        		item.selectAddonItemId = ''
        		return Object.assign({}, item)
        	})
	    },
	    methods: {
	    	initKeys: function(specs) {
	            for(var i=0;i<specs.length;i++) {
	                var curSpec = specs[i];
	                for(var j=0;j<curSpec.child.length;j++) {
	                    curSpec.child[j].isActive = false;
	                    curSpec.child[j].notClick = false;
	                }
	            }
	            this.specs = specs;
	        },
	        initProductItems: function(productItems) {
	            var productItemsObj = {};
	            for(var i=0;i<productItems.length;i++) {
	                var specsKey = productItems[i].specs.sort(function(itemA, itemB) {
	                    return parseInt(itemA.id) - parseInt(itemB.id);
	                }).map(item => item.id).join(";");
	                productItemsObj[specsKey] = productItems[i];
	            }

	            this.productItemsObj = productItemsObj;
	        },
	        //获得对象的key
	        getObjKeys(obj) {
	            if(obj !== Object(obj)) throw new TypeError('Invalid object');
	            var keys = [];
	            for(var key in obj)
	                if(Object.prototype.hasOwnProperty.call(obj, key))
	                    keys[keys.length] = key;
	            return keys;
	        },
	        addToSKUResult(combArrItem, sku) {
	            var key = combArrItem.join(";");
	            if(this.SKUResult[key]) { //SKU信息key属性·
	                this.SKUResult[key].count += sku.count;
	            } else {
	                this.SKUResult[key] = {
	                    count: sku.count
	                };
	            }
	        },
	        combinationConcat(aData) {
	            var result = [];
	            for(var i=1;i<=aData.length;i++) {
	                result = result.concat(aData.combination(i))
	            }
	            return result;
	        },
	        initSKU() {
	            var i, j, skuKeys = this.getObjKeys(this.productItemsObj);
	            for(i = 0; i < skuKeys.length; i++) {
	                var skuKey = skuKeys[i]; //一条SKU信息key
	                var sku = this.productItemsObj[skuKey]; //一条SKU信息value
	                var skuKeyAttrs = skuKey.split(";"); //SKU信息key属性值数组
	                skuKeyAttrs.sort(function(value1, value2) {
	                    return parseInt(value1) - parseInt(value2);
	                });
	                //对每个SKU信息key属性值进行拆分组合
	                var combArr = this.combinationConcat(skuKeyAttrs);
	                for(j = 0; j < combArr.length; j++) {
	                    this.addToSKUResult(combArr[j], sku);
	                }
	            }
	        },
	        initDisabledSpecItem() {
	            for(let i=0;i<this.specs.length;i++){
	                for(let j=0;j<this.specs[i].child.length;j++){
	                    if(this.SKUResult[this.specs[i].child[j].id] == null){
	                        this.specs[i].child[j].notClick = true;
	                    }
	                }
	            }
	        },
	        initDefaultSku(specArray) {
	        	var specList = this.productInfo.specs
			    for(var i=0;i<specList.length;i++) {
			      for(var j=0;j<specList[i].child.length;j++) {
			      	if(specArray[i]) {
				        if(specArray[i].id === specList[i].child[j].id) {
				          this.tabInfoChange(i, j)
				          break;
				        }
			        }
			      }
			    }
	        },
	        tabInfoChange(index,cindex,cid,e){
	            let specs = JSON.parse(JSON.stringify(this.specs))
	            let orderInfoChild = specs[index].child;/*当前点击的规格的所有子属性内容*/
	            //选中自己，兄弟节点取消选中
	            if(orderInfoChild[cindex].notClick != true){
	                if(orderInfoChild[cindex].isActive == true){
	                    orderInfoChild[cindex].isActive = false;
	                }else{
	                    for(let i=0;i<orderInfoChild.length;i++){
	                        orderInfoChild[i].isActive = false;
	                    }
	                    orderInfoChild[cindex].isActive = true;
	                }
	            }
	            
	            //已经选择的节点
	            let haveChangedId = [];
	            for(let i=0;i<specs.length;i++){
	                for(let j=0;j<specs[i].child.length;j++){
	                    if(specs[i].child[j].isActive == true){
	                        haveChangedId.push(specs[i].child[j].id);
	                    }
	                }
	            }
	            if(haveChangedId.length) {
	                //获得组合key价格
	                haveChangedId.sort(function(value1, value2) {
	                    return parseInt(value1) - parseInt(value2);
	                });
	                
	                this.haveChangedId = haveChangedId;

	                var len = haveChangedId.length;
	                
	                //用已选中的节点验证待测试节点 
	                let daiceshi = [];//待测试节点
	                let daiceshiId = [];
	                for(let i=0;i<specs.length;i++){
	                    for(let j=0;j<specs[i].child.length;j++){
	                        if(specs[index].child[cindex].id != specs[i].child[j].id){
	                            daiceshi.push({
	                                index:i,
	                                cindex:j,
	                                id: specs[i].child[j].id
	                            });
	                            daiceshiId.push(specs[i].child[j].id);
	                        }
	                    }
	                }

	                for(let i=0;i<haveChangedId.length;i++){
	                    var indexs = daiceshiId.indexOf(haveChangedId[i]);
	                    if (indexs > -1) {
	                        daiceshi.splice(indexs, 1);
	                    }
	                }
	                for(let i=0;i<daiceshi.length;i++){
	                    let testAttrIds = []; //从选中节点中去掉选中的兄弟节点
	                    let siblingsId = "";
	                    for(let m=0; m<specs[daiceshi[i].index].child.length; m++){
	                        if(specs[daiceshi[i].index].child[m].isActive == true){
	                            siblingsId = specs[daiceshi[i].index].child[m].id;
	                        }
	                    }
	                    if(siblingsId != ""){
	                        for(let j=0;j<len;j++){
	                            (haveChangedId[j] != siblingsId) && testAttrIds.push(haveChangedId[j]);
	                        }
	                    }else{
	                        testAttrIds = haveChangedId.concat();
	                    }
	                    testAttrIds = testAttrIds.concat(this.specs[daiceshi[i].index].child[daiceshi[i].cindex].id);
	                    testAttrIds.sort(function(value1, value2) {
	                        return parseInt(value1) - parseInt(value2);
	                    });
	                    if(!this.SKUResult[testAttrIds.join(';')]) {
	                        specs[daiceshi[i].index].child[daiceshi[i].cindex].notClick = true;
	                        specs[daiceshi[i].index].child[daiceshi[i].cindex].isActive = false;
	                    } else {
	                        specs[daiceshi[i].index].child[daiceshi[i].cindex].notClick = false;
	                    }
	                }
	            } else {
	            	this.haveChangedId = haveChangedId;
	                //设置属性状态
	                for(let i=0;i<specs.length;i++){
	                    for(let j=0;j<specs[i].child.length;j++){
	                        if(this.SKUResult[specs[i].child[j].id]){
	                            specs[i].child[j].notClick = false;
	                            specs[i].child[j].isActive = false;
	                        }else{
	                            specs[i].child[j].notClick = true;
	                            specs[i].child[j].isActive = false;
	                        }
	                    }
	                }
	            }
	            this.specs = specs;
	        },
	        setAddonItemId(addon, addonItem) {
	        	if(addon.selectAddonItemId == addonItem.addonItemId) {
	        		addon.selectAddonItemId = '';
	        	} else {
	        		addon.selectAddonItemId = addonItem.addonItemId;
	        	}
	        },
	        setAttributeItemId(attribute, attributeItem) {
	        	attribute.selectAttributeItemId = attributeItem.attributeItemId;
	        },
	        buyNow() {

	        },
	        addToCart(actionType) {
                if(this.productInfo.type == 'MULTIPLE') {
	        		if(!this.curProductItem.id) {
	        			this.$toast({
	                        message: '请选择商品规格',
	                        position: 'top',
	                        duration: 5000
	                    });
	                    return
	        		}
	        	}

	        	if(this.attributes.length) {
	        		if(this.btnDisabledStatus) {
	        			this.$toast({
	                        message: '请选择商品规格',
	                        position: 'top',
	                        duration: 5000
	                    });
	                    return
	        		}
	        	}

                var params = {
                    number: this.curCount,
                    productId: this.productInfo.id
                };
                if(this.productInfo.type == 'MULTIPLE') {
                	params.productItemId = this.curProductItem.id
                }

                params.attributes = this.attributes.map(item => {
                	return {
                		attributeId: item.attributeId,
                		attributeItemId: item.attributeItemId
                	}
                })

                params.addons = this.addons.filter(item=> item.selectAddonItemId).map(item => {
                	return {
                		addonId: item.addonId,
                		addonItemId: item.selectAddonItemId
                	}
                })

                this.cartCount += this.curCount;
                addToCart(params).then(() => {
                    this.$toast({
                        message: '已添加到购物车',
                        position: 'top'
                    });
                    this.joinCartModalVisible = false;
                    this.$emit('addCartSuccess');
                },() => {
                    this.$toast({
                        message: '添加到购物车失败',
                        type: 'error',
                        position: 'top'
                    });
                    this.cartCount--;
                })
	        },
	        desCount() {
	            if(this.curCount<=1) {
	                this.$toast({
	                    message: '数量最少为1',
	                    type: 'error',
	                    position: 'top'
	                });
	            } else {
	                this.curCount--;
	            }
	        },
	        addCount() {
	            if(this.curCount>=999) {
	                this.$toast({
	                    message: '数量较大暂不支持',
	                    type: 'error',
	                    position: 'top'
	                });
	            } else {
	                this.curCount++;
	            }
	        },
	        goToCheckOrder() {
	            utils.goToPage('check_order.html?productItemId='+this.curProductItem.id+"&number="+this.curCount);
	        },
	        cartModalChange(val) {
	        	if(val) {
	                document.body.style.overflow="hidden";
	            } else {
	                document.body.style.overflow="auto";
	            }
	            setTimeout(()=> {
	            	this.$emit("input", this.joinCartModalVisible);
	            }, 300)
	        }
	    }
	}
</script>